package service

import (
	"duoke/internal/dao"
	"duoke/internal/model/entity"
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gstr"
	"duoke/utils/orm"
	"duoke/utils/wechat_v3"
	"github.com/gin-gonic/gin"
	"github.com/syndtr/goleveldb/leveldb/errors"
)

var ShareOrder = new(shareOrderService)

type shareOrderService struct{}

func (s *shareOrderService) SaveAll(req *[]tables.ShareOrder) error {
	_, err := orm.Db.Insert(req)
	if err != nil {
		return err
	}
	return nil
}
func (s *shareOrderService) List(c *gin.Context, orderId string) (*model.ShareOrderList, error) {
	var couponOrder *entity.CouponOrder
	err := dao.CouponOrder.Ctx(c).Where("order_no = ? and pay_status = ?", orderId, 1).Scan(&couponOrder)
	if err != nil || couponOrder == nil {
		return nil, err
	}
	list := make([]tables.ShareOrder, 0)
	query := orm.Db.Desc("id")
	query.Where("order_id = ?", orderId)
	err = query.Find(&list)
	if err != nil {
		return nil, err
	}
	total := 0
	for _, item := range list {
		total += item.Amount
	}

	var coupon *entity.Coupon
	err = dao.Coupon.Ctx(c).Where("id", couponOrder.CouponId).Scan(&coupon)
	if err != nil || coupon == nil {
		return nil, err
	}
	info, err := SeparateAccounts.Info(c, "platform_commission",
		coupon.SubMchId)
	if err != nil {
		return nil, err

	}
	// 平台拿出分账金额
	totalFee := gconv.Float64(couponOrder.PayAmount) * gconv.Float64(info.PlatformCommission) / 100
	return &model.ShareOrderList{
		Amount:         gstr.Round(float64(totalFee) / 100),
		PlatformAmount: gstr.Round(float64(total) / 100),
		OrderList:      list,
	}, nil
}

func (s *shareOrderService) Del(c *gin.Context, id int) error {
	_, err := orm.Db.ID(id).Delete(new(tables.ShareOrder))
	if err != nil {
		return err
	}
	return nil
}

func (s *shareOrderService) Retransmission(c *gin.Context, orderId string) error {
	accountR, _ := Request.Account(c)
	res, err := AccountSetting.InfoById(accountR.Id, "miniprogram")
	if err != nil {
		return err
	}
	// 分账流程
	if err != nil {
		return err
	}
	var couponOrder *entity.CouponOrder
	err = dao.CouponOrder.Ctx(c).Where("order_no = ? and pay_status = ?", orderId, 1).Scan(&couponOrder)
	if err != nil || couponOrder == nil {
		return err
	}

	config := map[string]string{
		"sub_mch_id":     gconv.String(res["sub_mch_id"]),
		"transaction_id": couponOrder.TransactionId,
		"out_order_no":   couponOrder.OrderNo,
	}
	// 开始分账
	var shareOrder []entity.ShareOrder
	err = dao.ShareOrder.Ctx(c).Where("order_id", couponOrder.OrderNo).Scan(&shareOrder)
	var data []map[string]interface{}
	for _, order := range shareOrder {
		data = append(data, map[string]interface{}{
			"type":        order.Type,
			"account":     order.Account,
			"amount":      order.Amount,
			"description": order.Description,
		})
	}
	s2 := new(separateAccountsService)
	mergeData := s2.mergeData(data)
	share, err := wechat_v3.NewConfig(res).Share(config, mergeData)
	if err != nil {
		return err
	}
	if share.ResultCode == "FAIL" {
		return errors.New(share.ErrCodeDes)
	}
	return nil
}
